package com.bw.search.server.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.bw.common.core.utils.StringUtils;
import com.bw.search.common.EsProductModel;
import com.bw.search.server.service.EsService;
import com.bw.search.server.vo.SearchParam;
import com.bw.search.server.vo.SearchResult;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.Nested;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Service
public class EsServiceImpl implements EsService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public boolean productStatsUp(String esProductModels) {

        List<EsProductModel> esProductModels1 = JSON.parseArray(esProductModels, EsProductModel.class);

        BulkRequest bulkRequest = new BulkRequest();
        esProductModels1.stream().forEach(esProductModel -> {

            IndexRequest indexRequest = new IndexRequest();
            indexRequest.index("product");
            indexRequest.id(esProductModel.getSkuId().toString());
            indexRequest.source(JSON.toJSONString(esProductModel), XContentType.JSON);
            bulkRequest.add(indexRequest);

        });

        BulkResponse bulk = null;

        try {
            bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
        return bulk.hasFailures();

    }

    @Override
    public SearchResult search(SearchParam searchParam) throws IOException {

        SearchRequest searchRequest = buildSearchRequest(searchParam);

        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        SearchResult searchResult = analyerResponse(searchResponse, searchParam);
        return searchResult;
    }

    public SearchResult analyerResponse(SearchResponse searchResponse, SearchParam searchParam){

        SearchResult searchResult = new SearchResult();

        SearchHits hits = searchResponse.getHits();
        List skuEsModelList = new ArrayList();
        for (SearchHit hit : hits.getHits()) {

            String skuEsModelString = hit.getSourceAsString();
            EsProductModel skuEsModel = JSON.parseObject(skuEsModelString, EsProductModel.class);

            if(StringUtils.isNotBlank(searchParam.getKeyword())){
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                HighlightField skuTitleHighlightField = highlightFields.get("skuTitle");

                skuEsModel.setSkuTitle(skuTitleHighlightField.getFragments()[0].toString());
            }
            skuEsModelList.add(skuEsModel);
        }
        searchResult.setProducts(skuEsModelList);

        searchResult.setPageNum(searchParam.getPageNum());
        searchResult.setTotal(hits.getTotalHits().value);
        searchResult.setTotalPages(
                Long.valueOf(searchResult.getTotal()%20==0?searchResult.getTotal()/20:(searchResult.getTotal()/20+1)).intValue()
        );

        Aggregations aggregations = searchResponse.getAggregations();
        Terms brandIdAgg = aggregations.get("brandIdAgg");
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        for (Terms.Bucket bucket : brandIdAgg.getBuckets()) {

            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            brandVo.setBrandId(Long.valueOf(bucket.getKeyAsString()));

            Terms brandNameAgg = bucket.getAggregations().get("brandNameAgg");
            String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);

            brandVos.add(brandVo);
        }
        searchResult.setBrands(brandVos);

        Terms catalogIdAgg = aggregations.get("catalogIdAgg");
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        for (Terms.Bucket bucket : catalogIdAgg.getBuckets()) {

            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            String catalogId = bucket.getKeyAsString();
            catalogVo.setCatalogId(Long.valueOf(catalogId));
            Terms catalogNameAgg = bucket.getAggregations().get("catalogNameAgg");
            String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalogName);
            catalogVos.add(catalogVo);

        }
        searchResult.setCatalogs(catalogVos);

        ParsedNested attrAgg = aggregations.get("attrAgg");
        Terms attrIdAgg = attrAgg.getAggregations().get("attrIdAgg");
        List<SearchResult.AttrVo> attrs = new ArrayList<>();
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {

            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            attrVo.setAttrId(Long.valueOf(bucket.getKeyAsString()));

            Terms attrNameAgg = bucket.getAggregations().get("attrNameAgg");
            attrVo.setAttrName(attrNameAgg.getBuckets().get(0).getKeyAsString());

            Terms attrValueAgg = bucket.getAggregations().get("attrValueAgg");
            List<String> values = new ArrayList<>();
            for (Terms.Bucket attrValueAggBucket : attrValueAgg.getBuckets()) {
                values.add(attrValueAggBucket.getKeyAsString());
            }
            attrVo.setAttrValue(values);
            attrs.add(attrVo);

        }
        searchResult.setAttrs(attrs);
        return searchResult;
    }

    private SearchRequest buildSearchRequest(SearchParam searchParam){

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        if (StringUtils.isNotEmpty(searchParam.getKeyword())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle",searchParam.getKeyword()));
        }

        if (searchParam.getBrandId() != null){
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId",searchParam.getBrandId()));
        }

        if (searchParam.getCatalog3Id() != null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId",searchParam.getCatalog3Id()));
        }

        if (StringUtils.isNotBlank(searchParam.getSkuPrice())) {
            RangeQueryBuilder skuPrice = QueryBuilders.rangeQuery("skuPrice");
            String[] prices = searchParam.getSkuPrice().split("_");
            if (prices.length == 2) {
                skuPrice.gte(prices[0]);
                skuPrice.lte(prices[1]);
            } else if (searchParam.getSkuPrice().startsWith("_")) {
                skuPrice.lte(prices[1]);
            } else if (searchParam.getSkuPrice().endsWith("_")) {
                skuPrice.gte(prices[0]);
            }
            boolQueryBuilder.filter(skuPrice);
        }

        if(searchParam.getAttrs()!=null && searchParam.getAttrs().size()>0) {
            for (String attr : searchParam.getAttrs()) {
                String[] split = attr.split("_");
                String attrId = split[0];
                String[] attrValues = split[1].split(":");

                BoolQueryBuilder boolNestedQueryBuilder = QueryBuilders.boolQuery();
                boolNestedQueryBuilder.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                boolNestedQueryBuilder.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));

                NestedQueryBuilder attrs = QueryBuilders.nestedQuery("attrs", boolNestedQueryBuilder, ScoreMode.None);
                boolQueryBuilder.filter(attrs);

            }
        }

        sourceBuilder.query(boolQueryBuilder);

        if(StringUtils.isNotBlank(searchParam.getSort())) {
            String[] split = searchParam.getSort().split("_");
            sourceBuilder.sort(split[0], "asc".equalsIgnoreCase(split[1]) ? SortOrder.ASC : SortOrder.DESC);
        }

        sourceBuilder.from(0);
        sourceBuilder.size(20);


        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("skuTitle");
        highlightBuilder.preTags("<span style='color:skyblue;font-size:18px'>");
        highlightBuilder.postTags("</span>");

        sourceBuilder.highlighter(highlightBuilder);

        TermsAggregationBuilder brandIdAgg = AggregationBuilders.terms("brandIdAgg").field("brandId");
        TermsAggregationBuilder brandNameAgg = AggregationBuilders.terms("brandNameAgg").field("brandName");
        TermsAggregationBuilder brandImgAgg = AggregationBuilders.terms("brandImgAgg").field("brandImg");
        brandIdAgg.subAggregation(brandNameAgg);
        brandNameAgg.subAggregation(brandImgAgg);

        TermsAggregationBuilder catalogIdAgg = AggregationBuilders.terms("catalogIdAgg").field("catalogId");
        TermsAggregationBuilder catalogNameAgg = AggregationBuilders.terms("catalogNameAgg").field("catalogName");
        catalogIdAgg.subAggregation(catalogNameAgg);

        NestedAggregationBuilder attrAgg = AggregationBuilders.nested("attrAgg", "attrs");
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attrIdAgg").field("attrs.attrId");
        TermsAggregationBuilder attrNameAgg = AggregationBuilders.terms("attrNameAgg").field("attrs.attrName");
        TermsAggregationBuilder attrValueAgg = AggregationBuilders.terms("attrValueAgg").field("attrs.attrValue");
        attrAgg.subAggregation(attrIdAgg);
        attrIdAgg.subAggregation(attrNameAgg);
        attrIdAgg.subAggregation(attrValueAgg);

        sourceBuilder.aggregation(brandIdAgg);
        sourceBuilder.aggregation(catalogIdAgg);
        sourceBuilder.aggregation(attrAgg);

        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("product");
        searchRequest.source(sourceBuilder);

        return searchRequest;

    }



}
